package com.smileus.integration.caller.impl;

import java.net.ConnectException;
import java.net.MalformedURLException;

import com.alibaba.fastjson.JSONArray;
import com.caucho.hessian.client.HessianProxyFactory;
import com.smileus.entity.IntegrationLogs;
import com.smileus.entity.ServiceRouter;
import com.smileus.integration.caller.AbstractCaller;
import com.smileus.integration.caller.Caller;
import com.smileus.integration.provider.ServiceProvider;
import com.smileus.service.IntegrationLogsService;

/**
 * hessian caller实现类
 * 
 * @author dongheng
 * 
 */
public class HessianSyncCaller extends AbstractCaller implements Caller {
	private static HessianProxyFactory factory = new HessianProxyFactory();
	private static ServiceRouter cfgRouter = clusterService.getCurtServiceRouter();

	public String call(String serviceId, Object... params) {
		String jsonArray = null;
		String result = null;
		String url = null;
		IntegrationLogs logs = new IntegrationLogs();
		logs.setServiceId(serviceId);
		logs.setFromSys(cfgRouter.getSysDomain());
		logs.setFromHost(cfgRouter.getServiceHost());
		if (params == null) {
			jsonArray = "[]";
		} else {
			jsonArray = JSONArray.toJSONString(params);
		}
		logs.setInParam(jsonArray);
		try {
			url = getURL(serviceId);
			logs.setToSys(serviceId.split("\\.")[0]);
			logs.setToHost(toTargetHost(url));
			result = execute(serviceId, url, params);
			logs.setSuccess(1);
			logs.setOutParam(result);
		} catch (ConnectException e) {
			// RPC调用异常处理
			// TODO :
			/**
			 **异常情况下保障高可用： 1.可以尝试调用其他机器的服务 2.如果超过规定次数，远程启动备用服务器 3.短信、邮件通知系统owner
			 */
			if (clusterService.incrementAndCheck(url)) {
				// TODO：启用备用机器
				ServiceRouter sRouter = clusterService.getServiceRouterByPubAddress(url);
				if (sRouter.getServiceStatus() == 1) {
					sRouter.setServiceStatus(-1);// 设置为不可用状态
					clusterService.saveOrUpdateServiceRouter(sRouter);
				}
				clusterService.clusterRefresh();
				clusterService.sendMessage(sRouter);// 短信邮件通知
			}
			// 记录异常日志
			logs.setSuccess(-1);
			logs.setOutParam(e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		IntegrationLogsService.saveLogs(logs);
		return result;
	}

	/**
	 * 执行方法，显示第抛出ConnectException
	 * 
	 * @param serviceId
	 * @param param
	 * @return
	 * @throws ConnectException
	 * @throws MalformedURLException
	 */
	public String execute(String serviceId, String url, Object... param) throws ConnectException, MalformedURLException {
		ServiceProvider provider = (ServiceProvider) factory.create(ServiceProvider.class, url);
		return provider.doService(serviceId, JSONArray.toJSONString(param));
	}
}
